package com.zhuhjay.util;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.zhuhjay.model.domain.HttpResult;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

/**
 * @author ZhuHJay
 * @date 2023/4/26 11:04
 */
public class ServletUtils {

    /** 获取当前请求request对象 */
    public static HttpServletRequest getRequest() {
        return getRequestAttributes().getRequest();
    }

    /** 获取当前请求response对象 */
    public static HttpServletResponse getResponse() {
        return getRequestAttributes().getResponse();
    }

    /** 获取当前请求session对象 */
    public static HttpSession getSession() {
        return getRequest().getSession();
    }

    public static ServletRequestAttributes getRequestAttributes() {
        return (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
    }

    public static void writeJsonResult(HttpResult<?> httpResult) {
        try {
            ObjectMapper mapper = new ObjectMapper();
            HttpServletResponse response = getResponse();
            response.setContentType("application/json;charset=utf-8");
            response.getWriter().write(mapper.writeValueAsString(httpResult));
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

}
